<template>
  <div class="store-manage">
    <!-- 用户信息展示 -->
    <div class="user-info">
      <span>库管员姓名：{{ user.name }}</span>
      <span style="margin-left: 20px">登录手机号：{{ user.phone }}</span>
    </div>

    <!-- 树形选择 -->
    <el-tree
      v-model="checkedKeys"
      :data="storeTree"
      :props="defaultProps"
      show-checkbox
      node-key="id"
      highlight-current
      default-expand-all
      style="margin-top: 20px"
    />

    <!-- 提交按钮 -->
    <el-button type="primary" style="margin-top: 20px" @click="handleSubmit">
      提交
    </el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import { setPermission, updatePermission, getPermission, userPermission } from "@/api/set/keeper.js";

// 路由带过来的用户信息
const route = useRoute();
const user = ref({
  id: Number(route.query.id),  // 用户 id
  name: route.query.name || "未知",
  phone: route.query.phone || "",
});

// 仓库树
const storeTree = ref([]);

// el-tree props 配置
const defaultProps = {
  children: "children",
  label: "name",
};

// 选中的节点id数组
const checkedKeys = ref([]);

// 保存用户已有的权限 (用于对比)
const oldPermissionIds = ref([]);

// 加载仓库树 & 用户权限
const loadData = async () => {
  try {
    const res1 = await getPermission();
    if (res1.code === 200) {
      storeTree.value = res1.data;
    }

    const res2 = await userPermission(user.value.id);
    if (res2.code === 200) {
      const ids = res2.data.map((item) => item.id);
      checkedKeys.value = ids;
      oldPermissionIds.value = [...ids]; // 保存原来的权限
    }
  } catch (e) {
    ElMessage.error("加载数据失败");
  }
};

// 提交修改
const handleSubmit = async () => {
  const userId = user.value.id;
  const newIds = checkedKeys.value;

  // diff 对比
  const addIds = newIds.filter((id) => !oldPermissionIds.value.includes(id));
  const delIds = oldPermissionIds.value.filter((id) => !newIds.includes(id));

  try {
    // 新增权限
    for (let storeId of addIds) {
      await setPermission({ id: 0, storeId, userId });
    }
    // 删除或更新权限
    for (let storeId of delIds) {
      await updatePermission({ id: 0, storeId, userId });
    }

    ElMessage.success("权限更新成功");
    oldPermissionIds.value = [...newIds]; // 更新旧权限
  } catch (e) {
    ElMessage.error("提交失败");
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.store-manage {
  padding: 20px;
}
.user-info {
  margin-bottom: 10px;
}
</style>